package models

import (
	"github.com/beego/beego/v2/client/orm"
)

type ErpCuring struct {
	Id                 int64
	DepartmentId       int64
	Number             string
	BrandId            int64
	BrandName          string
	ProductTypeid      int //20隐形眼镜50护理产品
	Name               string
	CuringType         int //养护类型1重点2临时
	Status             int //计划状态1养护中2已完成
	CreatedAt          int64
	AlreadyCheckNumber int64
	NeedCheckNumber    int64
	TimeLimit          string
}

func (a *ErpCuring) TableName() string {
	return ErpCuringTableName()
}
func ErpCuringTableName() string {
	return TableName("erp_curing")
}

//盘点主表查询项
type ErpCuringQueryParam struct {
	BaseQueryParam
	Number     string `json:"number"`
	Depid      int64  `json:"depid"`
	CuringType string `json:"curing_type"`
	Status     string `json:"status"`
}

//查询条件
func ErpCuringQuerySeter(params *ErpCuringQueryParam) orm.QuerySeter {

	query := orm.NewOrm().QueryTable(ErpCuringTableName())

	cond := orm.NewCondition()
	if params.Depid > 0 {
		cond = cond.And("department_id", params.Depid)
	}
	if len(params.Number) > 0 { //搜索直接查规格名
		cond = cond.And("Number__eq", params.Number)
	}
	if len(params.CuringType) > 0 {
		cond = cond.And("CuringType", params.CuringType)
	}
	if len(params.Status) > 0 {
		cond = cond.And("Status", params.Status)
	}

	query = query.SetCond(cond)

	return query
}

func ErpCuringPageList(params *ErpCuringQueryParam) ([]*ErpCuring, int64) {

	ls := make([]*ErpCuring, 0)

	query := ErpCuringQuerySeter(params)

	total, _ := query.Count()

	query.OrderBy("-Id").Limit(params.Limit, params.Offset).All(&ls)

	return ls, total
}

func queryCuringTimeSoltSeter(starttime, endtime int64) orm.QuerySeter {
	query := orm.NewOrm().QueryTable(ErpCuringTableName())
	cond := orm.NewCondition()
	cond = cond.AndCond(cond.And("CreatedAt__gte", starttime).And("CreatedAt__lte", endtime))
	query = query.SetCond(cond)

	return query
}

//按时间段获取销售数据
func QueryCuringTimeSoltSeter(starttime, endtime int64) []*ErpCuring {
	data := make([]*ErpCuring, 0)
	queryCuringTimeSoltSeter(starttime, endtime).OrderBy("-id").All(&data)
	return data
}

func QueryCuringSoltSeterCount(starttime, endtime int64) int64 {
	count, _ := queryCuringTimeSoltSeter(starttime, endtime).Count()
	return count
}

func GetErpCuringById(id int64) (*ErpCuring, error) {

	r := new(ErpCuring)
	err := orm.NewOrm().QueryTable(ErpCuringTableName()).Filter("id", id).One(r)
	if err != nil {
		return nil, err
	}

	return r, nil
}
